<script lang="ts" setup>
  import { useVbenDrawer } from '@vben/common-ui';

  import { type DrawerStatus } from '#/adapter';
  import { editDepartment, addDepartment } from '#/api';

  const formStatus = ref<DrawerStatus>('CREATE');
  const formTitle = computed<string>(() => {
    return unref(formStatus) === 'CREATE'
      ? '创建部门'
      : unref(formStatus) === 'VIEW'
        ? '查看部门信息'
        : '修改部门信息';
  });

  const emit = defineEmits<{ reload: [] }>();

  const [Drawer, drawerApi] = useVbenDrawer({
    onCancel() {
      drawerApi.close();
    },
    async onConfirm() {
      await formApi.validate();
      const formValues = await formApi.getValues();
      await (formStatus.value === 'CREATE'
        ? addDepartment(formValues)
        : editDepartment(formValues));
      emit('reload');
      drawerApi.close();
    },
    onOpenChange(isOpen: boolean) {
      if (isOpen) {
        const { status, record } = drawerApi.getData();
        formStatus.value = status;
        if (status !== 'CREATE') formApi.setValues(record);
        formApi.setState({
          commonConfig: { disabled: status === 'VIEW' },
        });
      }
    },
  });

  import { useVbenForm, withDefaultFormConfig } from '#/adapter';
  import { getFormSchema } from './data';
  import { computed, ref, unref } from 'vue';

  const [Form, formApi] = useVbenForm(
    withDefaultFormConfig({
      schema: getFormSchema(),
      wrapperClass: 'grid-cols-1',
    }).build(),
  );
</script>
<template>
  <Drawer :title="formTitle">
    <Form></Form>
  </Drawer>
</template>
